import 'dart:isolate';
import 'dart:ui';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sleek_circular_slider/sleek_circular_slider.dart';
import 'dart:math';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:open_file/open_file.dart';

class UpdatePage extends StatefulWidget {
  @override
  _UpdatePageState createState() => _UpdatePageState();
}

class _UpdatePageState extends State<UpdatePage> {
  int _progessShow = 0; //显示的进度
  int _progessReal = 0; //真实的进度
  Duration timeout = Duration(milliseconds: 500); //定时
  String _direcotry = '';
  String _apkName = 'doFlutter.apk';
  ReceivePort _port = ReceivePort(); //下载插件通信使用

  @override
  void initState() {
    super.initState();
    initIsolateNameServer(); //设置通道监听
    initPath(); //设置路径
  }

  @override
  void dispose() {
    //销毁通道监听
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  //进度显示过渡效果
  _progessRun() {
    if (_progessReal > _progessShow) {
      setState(() {
        _progessShow++;
        print('过渡：' + _progessShow.toString());
      });
      Timer(timeout, () {
        _progessRun();
      });
    }
  }

  //设置进度
  _progessSetValue(num) {
    _progessReal = num;
    _progessRun();
  }

  //监听通道
  void initIsolateNameServer() {
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      if (status == DownloadTaskStatus.running) {
        print('下载中：' + progress.toString());
        _progessSetValue(progress);
      }
      if (status == DownloadTaskStatus.failed) {
        print('下载失败');
      }
      if (status == DownloadTaskStatus.complete) {
        print('下载完成');
        // FlutterDownloader.open(taskId: id);
        _installApk();
      }
    });
  }

  //设置路径
  Future initPath() async {
    final dir = await getExternalStorageDirectory();
    String path = dir.path;

    setState(() {
      _direcotry = path;
    });

    //判断文件是否存在
    File file = File(path + '/' + _apkName);
    if (await file.exists()) {
      await file.delete();
    }
    executeDownload('http://192.168.31.60:8286/app.apk');
  }

  //下载
  Future<void> executeDownload(String url) async {
    print('准备下载');
    //初始化
    WidgetsFlutterBinding.ensureInitialized();
    await FlutterDownloader.initialize(
        debug: true // optional: set false to disable printing logs to console
        );
    FlutterDownloader.registerCallback(downLoadCallback);
    //创建新的下载任务
    final taskId = await FlutterDownloader.enqueue(
      url: url,
      savedDir: _direcotry,
      fileName: _apkName,
      showNotification:
          true, // show download progress in status bar (for Android)
      openFileFromNotification:
          true, // click on notification to open downloaded file (for Android)
    );
  }

  static void downLoadCallback(
      String id, DownloadTaskStatus status, int progress) {
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  //安装
  Future<Null> _installApk() async {
    //为了显示效果
    if (100 > _progessShow) {
      Timer(timeout, () {
        _installApk();
      });
    } else {
      //正真的安装代码
      await OpenFile.open(_direcotry + '/' + _apkName);
    }
  }

  //进度条
  Widget _progess() {
    final customWidths = CustomSliderWidths(trackWidth: 1, progressBarWidth: 5);
    final customColors = CustomSliderColors(
        dotColor: Colors.white.withOpacity(0.5),
        trackColor: HexColor('#000000').withOpacity(0.1),
        progressBarColors: [
          HexColor('#F7E4FF').withOpacity(0.3),
          HexColor('#4E09ED').withOpacity(0.5),
          HexColor('#76E2FF').withOpacity(0.5),
        ],
        dynamicGradient: true,
        shadowColor: HexColor('#55B3E4'),
        shadowMaxOpacity: 0.02);
    final slider = SleekCircularSlider(
        appearance: CircularSliderAppearance(
          size: 200,
          startAngle: 0,
          angleRange: 360,
          customWidths: customWidths,
          customColors: customColors,
        ),
        initialValue: _progessShow.toDouble());
    return slider;
  }

  Widget _button(context) {
    return RaisedButton(
      onPressed: () => {_progessSetValue(Random().nextInt(100))},
      child: Text('new value'),
    );
  }

  Widget _buildBody() {
    return Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _progess(),
          Center(
            child: Text('升级中，请稍后。'),
          ),
          _button(context)
        ]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('升级'),
      ),
      body: _buildBody(),
    );
  }
}

class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF' + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}
